#!/usr/bin/evn python
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
   文件名称 :     singleton_helper
   文件功能描述 :   功能描述
   创建人 :       小钟同学
   创建时间 :          2021/7/15
-------------------------------------------------
   修改描述-2021/7/15:         
-------------------------------------------------
"""


def Singleton(cls):
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    def __clear__():
        _instance.clear()

    _singleton.__clear__ = __clear__

    return _singleton


class SingletonMetaclass(type):
    '''
    用法示例
    class Xoo(object):
        __metaclass__ = SingletonMetaclass #在代码执行到这里的时候，元类中的__new__方法和__init__方法其实已经被执行了，而不是在Xoo实例化的时候执行。且仅会执行一次。
    '''

    def __init__(self, *args, **kwargs):
        self.__instance = None
        super(SingletonMetaclass, self).__init__(*args, **kwargs)

    def __call__(self, *args, **kwargs):
        if self.__instance is None:
            self.__instance = super(SingletonMetaclass, self).__call__(*args, **kwargs)
        return self.__instance


import threading


class SingletonType(type):
    _instance_lock = threading.Lock()

    def __call__(cls, *args, **kwargs):
        if not hasattr(cls, "_instance"):
            with SingletonType._instance_lock:
                if not hasattr(cls, "_instance"):
                    cls._instance = super(SingletonType, cls).__call__(*args, **kwargs)
        return cls._instance
